<template>
  <div class="app-container">
    <el-row>
      <el-col :span="6" class="tl-left-tree">
        <!-- 树 -->
        <el-input v-model="queryTreeParam.qry_name" placeholder="根据名称筛选" @keyup.enter.native="filterTree" ref="treeSearch">
          <el-button current-node-key="" slot="append" icon="el-icon-search" @click="filterTree"></el-button>
        </el-input>
        <el-scrollbar ref="treeScroll" :style="{ height: treeHeight + 'px' }" resizable-key="treeHeight" :resizable-reduce="20" :resizable-refs="['treeSearch']">
					<el-button type="text" size="mini" style="width: 28%" @click="toProvince()">展开到省</el-button>
          <el-button type="text" size="mini" style="width: 28%" @click="toCity()">展开到市</el-button>
          <el-button type="text" size="mini" style="width: 28%" @click="toMatch()">展开到县</el-button>
          <el-tree v-if="refreshTree" class="tl-tree" ref="tree" :data="treeData" node-key="id" :default-expand-all="false" highlight-current :expand-on-click-node="false" :default-expanded-keys="expandArray" @node-click="doTreeQuery" :filter-node-method="filterTreeNode" :props="TreeProps" ></el-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="18">
        <el-row>
          <!-- 查询 -->
          <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" v-if="isHeaderDisplay">
            <template slot="search">
              <el-form-item label="区域名称">
                <el-input v-model="queryParam.qry_name" placeholder=""></el-input>
              </el-form-item>
              <el-form-item label="授权人员">
                <el-input v-model="queryParam.qry_user" placeholder="输入姓名或工号"></el-input>
              </el-form-item>
            </template>
          </tl-list-search>
        </el-row>
        <el-card>
          <el-row>
            <!-- 工具栏 -->
            <tl-list-toolbar ref="toolbar" @add="openAddDialog('editForm')" @exportExcel="doExportExcel" @deleteBatch="doDeleteBatch" @refresh="doRefresh" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :disableDeleteBatch="selectedRowKeys.length <= 0" :isDisplayDeleteBatch="false" :isDisplayExport="false" :isDisplayAdd="isProvince"> </tl-list-toolbar>
          </el-row>
          <el-row ref="selector">
            <!-- 列表选择 -->
            <div class="table-alert-div">
              <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
                <template slot="title">
                  已选择&nbsp;<a style="font-weight: bold;">{{ selectedRowKeys.length }}</a
                  >项&nbsp;&nbsp;
                  <a style="font-weight: bold;margin-left: 24px" @click="doClearSelected">全部清空</a>
                </template>
              </el-alert>
            </div>
          </el-row>
          <el-row>
            <el-table ref="mainTable" class="tl-table" :height="tableHeight" resizable-key="tableHeight" :resizable-reduce="42" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" style="width: 100%;" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClickByAuthority" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName" :default-sort="{ prop: 'code', order: 'ascending' }">
              <el-table-column type="selection" width="55px" fixed="left"></el-table-column>
              <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
              <el-table-column prop="name" label="区域名称" width="150px" sortable="custom" sort-by="name" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="disparealevel" label="级别" width="80px" sortable="custom" sort-by="arealevel" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="areaauthorizationusername" label="区域授权人员" width="150px" sortable="custom" sort-by="areaauthorizationusercode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="parentname" label="上级区域" min-width="100px" sortable="custom" sort-by="parentid" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="dispdeptcommoncode" label="一级部门" width="80px" sortable="custom" sort-by="deptcommoncode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column prop="useful" label="启用" width="60px" sortable="custom" sort-by="useful" align="center" header-align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.useful == '1'" type="success">是</el-tag>
                  <el-tag v-else type="danger">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="90px" v-slot="scope" fixed="right">
                <el-dropdown trigger="hover">
                  <el-button type="text" icon="el-icon-s-operation" style="margin-center">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                  <el-dropdown-menu>
                    <el-dropdown-item type="text" icon="el-icon-circle-plus-outline" v-if="isAuthorized(scope.row) && scope.row.useful === '1'" @click.native="openAddDialog('cityEditRef', scope.row)">新增下级</el-dropdown-item>
                    <!-- <el-dropdown-item type="text" icon="el-icon-circle-plus-outline" @click.native="openAddDialog('cityEditRef', scope.row)">新增下级</el-dropdown-item> -->
                    <el-dropdown-item type="text" icon="el-icon-view" @click.native="openViewDialog('editForm', scope.row.id)">查看</el-dropdown-item>
                    <el-dropdown-item type="text" icon="el-icon-edit" @click.native="openEditDialog('editForm', scope.row.id)" v-show="canBeEdited(scope.row)" :disabled="disableEdit(scope.row)">编辑</el-dropdown-item>
                    <el-tooltip class="item" effect="dark" content="可变更负责人和区域顺序" placement="left">
                      <el-dropdown-item type="text" icon="el-icon-user" @click.native="openEditDialog('changePeople', scope.row.id)" v-show="canBeChanged(scope.row)">变更</el-dropdown-item>
                    </el-tooltip>
                    <el-dropdown-item type="text" icon="el-icon-circle-close" @click.native="openEnableDialog('editForm', scope.row.id)" v-show="hasAreaPermission(scope.row) && scope.row.useful === '1'">禁用区域</el-dropdown-item>
                    <el-dropdown-item type="text" icon="el-icon-circle-check" @click.native="openEnableDialog('editForm', scope.row.id)" v-show="hasAreaPermission(scope.row) && scope.row.useful === '0'">启用区域</el-dropdown-item>

                    <el-dropdown-item type="text" icon="el-icon-delete" @click.native="doDelete(scope.row.id)" v-show="canBeEdited(scope.row)" :disabled="disableEdit(scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-table-column>
            </el-table>
          </el-row>
          <!-- 列表分页 -->
          <el-row class="pagebar" ref="pager">
            <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
          </el-row>
        </el-card>
      </el-col>
      <!-- 编辑界面 -->
      <tl-edit ref="editForm" :cityInCharge="cityInCharge" :isBspOperator="isBspOperator" :isCfoOrPm="isCfoOrPm" :userLevel="userLevel" :BSPOperatorParam="BSPOperatorParam" :dataParam="dataParam" @refresh="doAllRefresh"></tl-edit>
      <tl-change-people ref="changePeople" @refresh="doAllRefresh"></tl-change-people>
      <tl-city-edit ref="cityEditRef" :cityInCharge="cityInCharge" :dataParam="dataParam" @refresh="doAllRefresh"></tl-city-edit>
    </el-row>
  </div>
</template>
<script>
/** mixins */
import { mixin_tree_list } from '@tapui/mixins/mixin_tree_list'
import { getAction, putAction, postAction } from '@tapui/utils/http'
/** 子组件 */
import tlEdit from './edit'
import tlCityEdit from './editCityData'
import tlChangePeople from './changePeople'
import { MMS_AREA_LEVEL, OPERATOR_ROLE } from '@/const/const'
export default {
	name: 'mmsProvinceCityMatchinfo',
	mixins: [mixin_tree_list],
	components: { tlEdit, tlCityEdit, tlChangePeople },
	data() {
		return {
			urlPrefix: '/mms/provinceCityMatchinfo/',
			url: {
				queryCodeList: '/mms/provinceCityMatchinfo/dataCodeList',
				whetherCfoOrPm: '/mms/provinceCityMatchinfo/whetherCfoOrPm',
				queryCity: '/mms/provinceCityMatchinfo/queryCity',
				importExcel: '/mms/provinceCityMatchinfo/importExcel',
				queryLevel: '/mms/provinceCityMatchinfo/queryLevel',
				queryDeptCommonCode: '/mms/provinceCityMatchinfo/queryDeptCommonCode'
			},
			// 排序参数
			sorterInfo: {
				sidx: 'sortcode asc,id',
				sord: 'asc'
			},
			// 数列表关联字段
			treeQueryKey: 'qry_parentid',
			TreeProps: {
				// disabled: function(data, node) {
				// 		return data.children.length < 1
				// }
			},
			// 查询条件
            BSPOperatorParam: {
                BSPOperatorDept: '',
                BSPOperatorPID: '',
                BSPOperatorPName: ''
            },
			queryParam: {},
			codeModel: {},
			isCfoOrPm: false,
			cityInCharge: [],
			dataParam: undefined,
			expandArray: [],
			refreshTree: true,
			deptCommonInfo: undefined,
            TreeQueryMode: {
            // eslint-disable-next-line key-spacing
            TreeDlick : '0', // 树点击查询
            TreeList: '1' // 树列表查询
            },
			userLevel: ''
		}
	},
	computed: {
		isBspOperator() {
			let rolelist = this.$store.getters.roles
			let opRole = rolelist.filter(role => {
				return role === OPERATOR_ROLE
			})
			return opRole.length > 0
		},
		// 新增按钮显示/隐藏
		isProvince() {
			// 运营人员一直显示
			if (this.isBspOperator) {
				return true
			} else if (this.userLevel === '0' && this.selectTreeNode.id) {
				// 只有左树选中的是一级部门时显示新增按钮
				if (this.selectTreeNode.id.length <= 4) {
					return true
				}
			}
			return false
		},
		// 编辑和删除按钮的显示/隐藏
		canBeEdited(row) {
			return row => {
				// 判断是否已启用或处于审批中。已启用或处于审批中则不可编辑，隐藏；未启用则显示
				if (row.useful === '1' || row.state === 1) {
					return false
				} else {
					return true
				}
			}
		},
		// 变更按钮显示/隐藏判断
		canBeChanged(row) {
			return row => {
				// 运营人员、省总和CFO可变更全部区域（角色不同，范围不一样）
				if (this.isBspOperator || this.isCfoOrPm || this.userLevel === '0') {
					return true
				}
				// 省级负责人只可变更自己负责的省级区域
				if (row.arealevel === MMS_AREA_LEVEL.province) {
					let userCodes = row.areaauthorizationusercode.split(',')
					if (userCodes.includes(this.user.code)) {
						return true
					}
				} else if (row.arealevel === MMS_AREA_LEVEL.country) {
					// 只有当县级区域已启用才可变更
					// 市级负责人可变更县级区域
					if (row.useful === '1' && this.cityInCharge) {
						if (this.cityInCharge.includes(row.parentname)) {
							return true
						}
					}
				}
				return false
			}
		},
		// 新增下级数据
		isAuthorized(row) {
			return row => {
				// 只有省级、市级数据可新增下级数据
				if (row.arealevel !== MMS_AREA_LEVEL.country) {
					let userCodes = row.areaauthorizationusercode.split(',')
					// 省级权限
					if (this.userLevel === '0' || this.isCfoOrPm) {
						return true
					} else if (this.userLevel === '1' && userCodes.includes(this.user.code) && row.arealevel === MMS_AREA_LEVEL.city) {
						return true
					}
				}
				return false
			}
		},
		// 编辑禁用权限判断
		disableEdit(row) {
			return row => {
				// 省级区域不用审批，只需判断权限
				if (row.arealevel === MMS_AREA_LEVEL.province) {
					// 省总或CFO可编辑所有省级区域；省级负责人只可编辑自己管理的省级区域
					if (this.isCfoOrPm || this.userLevel === '0') {
						return false
					}
				}
				// 市级区域
				if (row.arealevel === MMS_AREA_LEVEL.city) {
					// 省级权限可修改任何市级区域
					if (this.userLevel === '0') {
						return false
					}
				}
				// 县级区域
				if (row.arealevel === MMS_AREA_LEVEL.country) {
					// 市级负责人可编辑所有县级区域
					if (this.userLevel === '1' || this.userLevel === '0') {
						return false
					}
				}
				return true
			}
		},
		hasAreaPermission(row) {
			return function(row) {
				// 管理员或省总都可启用全部区域
				if (this.isBspOperator || this.isCfoOrPm || this.userLevel === '0') {
					return true
				}
				// 省级负责人只可启用自己负责的省级区域
				if (row.arealevel === MMS_AREA_LEVEL.province) {
					let userCodes = row.areaauthorizationusercode.split(',')
					if (this.userLevel === '0' && userCodes.includes(this.user.code)) {
						return true
					}
				} else if (row.arealevel === MMS_AREA_LEVEL.country) {
					// 市级负责人可启用县级区域
					if (this.userLevel === '1') {
						return true
					}
				}
			}
		}
	},
	async created() {
		this.queryLevel()
		this.isCfoOrPm = await this.whetherCfoOrPm()
		this.cityInCharge = await this.queryCity()
		this.deptCommonInfo = await this.queryDeptCommonCode()
	},
	methods: {
		// 展示到省级
    toProvince() {
      this.expandArray = []
      this.$set(this.queryTreeParam, 'qry_name', '')
      // 直接用一级部门级数据
			if (this.treeData[0].children === null) {
         return
			}
      this.treeData[0].children.forEach((topitem) => {
        this.expandArray.push(topitem.id)
      })
      this.$nextTick(() => {
        this.refreshTree = true
      })
      this.refreshTree = false
    },
		// 展示到市级
    toCity() {
      this.expandArray = []
      this.$set(this.queryTreeParam, 'qry_name', '')
      // 直接用一级部门级数据
			if (this.treeData[0].children === null) {
         return
			}
      this.treeData[0].children.forEach((topitem) => {
        if (topitem.children.length > 0) {
          // 遍历一级部门下省级数据
          topitem.children.forEach((provinceitem) => {
            // if (provinceitem.treeFullData.arealevel === '0') {
              this.expandArray.push(provinceitem.id)
            // }
          })
        }
      })
      this.$nextTick(() => {
        this.refreshTree = true
      })
      this.refreshTree = false
    },
		// 展示到县级
    toMatch() {
      this.expandArray = []
      this.$set(this.queryTreeParam, 'qry_name', '')
      // 直接用一级部门级数据
			if (this.treeData[0].children === null) {
         return
			}
      this.treeData[0].children.forEach((topitem) => {
        if (topitem.children.length > 0) {
          // 遍历一级部门下省级数据
          topitem.children.forEach((provinceitem) => {
						if (provinceitem.children !== null) {
            if (provinceitem.children.length > 0) {
              // 遍历省级下市级数据
              provinceitem.children.forEach((cityitem) => {
                // if (cityitem.treeFullData.arealevel === '1') {
                  this.expandArray.push(cityitem.id)
                // }
              })
            }
						} else {
               this.expandArray.push(provinceitem.id)
						}
          })
        }
      })
      this.$nextTick(() => {
        this.refreshTree = true
      })
      this.refreshTree = false
    },
       // 逆回节点查找一级部门code
       getDeptCode(node) {
				this.toProvince()
        if (!node) {
            return ''
        } else if (node.level === 2) {
            return node.data.code
        } else {
           return this.getDeptCode(node.parent)
        }
       },
      // 点击时记录数据
      doTreeQuery(treeNode, node) {
      // 查询方式为树节点查询
      // 记录节点信息
      this.BSPOperatorParam.BSPOperatorDept = this.getDeptCode(node)
      if (node && node.level !== 1) {
        this.BSPOperatorParam.BSPOperatorPID = treeNode.id
        this.BSPOperatorParam.BSPOperatorPName = treeNode.name
      } else {
        this.BSPOperatorParam.BSPOperatorPID = ' '
        this.BSPOperatorParam.BSPOperatorPName = ' '
      }
      this.treeQueryMode = this.TreeQueryMode.TreeDlick
      this.selectTreeNode = treeNode
      this.pageInfo.currentPage = 1
      this.loadList({})
      // if (!this.beforeLoadData()) return
      // let params = this.getQueryParams()
      // this.doListQuery(params)
    },
		// 查询用户权限（省/市）
		queryLevel() {
			getAction(this.url.queryLevel, {}).then(res => {
				if (res.success) {
					this.userLevel = res.result.userLevel
				} else {
					this.$tap.alert(res.message)
				}
			})
		},
		// 表格双击事件
		doRowDbClickByAuthority(row, column, event) {
			this.rowDbClickActionType = 'edit'
			// 区域启用后不可编辑
			if (row.useful === '1') {
				this.rowDbClickActionType = 'view'
			} else if (row.arealevel === MMS_AREA_LEVEL.country) {
				// 无市级区域管理权限的省级负责人不可编辑
				if (!this.cityInCharge) {
					this.rowDbClickActionType = 'view'
				} else if (!this.cityInCharge.includes(row.parentname)) {
					// 无此县级区域上级的市级区域管理权限的省级负责人不可编辑
					this.rowDbClickActionType = 'view'
				}
			}
			this.doRowDbClick(row, column, event)
		},
		// 查询是否为省总或CFO
		whetherCfoOrPm() {
			return getAction(this.url.whetherCfoOrPm, {})
				.then(res => {
					if (res.success) {
						return res.result
					} else {
						this.$tap.alert(res.message, 'warning')
						return false
					}
				})
				.catch(err => {
					this.$tap.alert(err.message, 'warning')
				})
		},
		// 查询当前用户管理的市级区域
		queryCity() {
			return getAction(this.url.queryCity, {})
				.then(res => {
					if (res.success) {
						return res.result
					} else {
						this.$tap.alert(res.message, 'warning')
						return false
					}
				})
				.catch(err => {
					this.$tap.alert(err.message, 'warning')
				})
		},
		// 查询当前用户的一级部门（仅当用户为省总/CFO时需要）
		queryDeptCommonCode() {
			return getAction(this.url.queryDeptCommonCode, {})
				.then(res => {
					if (res.success) {
						return res.result
					} else {
						this.$tap.alert(res.message, 'warning')
						return false
					}
				})
				.catch(err => {
					this.$tap.alert(err.message, 'warning')
				})
		},
		beforeLoadData() {
			this.queryParam.qry_id = undefined
			// 若使用查询条件则不需要拼接id
			if (!this.queryParam.qry_name && !this.queryParam.qry_user) {
				this.queryParam.qry_id = this.selectTreeNode.id
			}
			return true
		},
		/** 打开新增对话框之前*/
		beforeOpenAddDialog(editForm, rowData) {
			if (editForm === 'cityEditRef') {
				this.dataParam = rowData
			} else if (editForm === 'editForm') {
				this.dataParam = this.deptCommonInfo
			}
			return true
		},
		/** 打开新增对话框之前 */
		afterOpenAddDialog(editForm, rowData) {
			if (!this.isBspOperator && editForm === 'editForm') {
				this.$tap.alert('新增按钮只可新增省级数据！可点击省/市级数据的更多-“新增下级数据”添加市/县级数据！')
			}
			return true
		},
		/** 打开禁用对话框*/
		openEnableDialog(editForm, id) {
			this.$refs[editForm].id = id
			this.$refs[editForm].isAdd = false
			this.$refs[editForm].visible = true
			this.$refs[editForm].changeUseful = true
			this.$refs[editForm].disableEditSubmit = true
			let that = this
			setTimeout(() => {
				that.clickRowkey = id
			}, 100)
		}
	}
}
</script>
<style lang="scss" scoped></style>
